package logic

import (
	"context"
	"errors"
	"fmt"
	"home/model/mysql"
	"home/pkg"
	"math/rand"

	"home/homerpc/homerpc"
	"home/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ResterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewResterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResterLogic {
	return &ResterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 注册
func (l *ResterLogic) Rester(in *homerpc.ResterRequest) (*homerpc.ResterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("tel = ?", in.Tel).Find(&user)
	if user.ID != 0 {
		return nil, errors.New("当前用户已存在，请更换")
	}

	m := mysql.User{
		Account:   in.Account,
		Password:  pkg.MD5(in.Password),
		Tel:       in.Tel,
		Name:      fmt.Sprintf("用户_%d", rand.Intn(10000)),
		HeadImage: "https://bpic.588ku.com/original_origin_min_pic/19/10/04/a321f23dd346c61646a546ad9cc9194d.jpg!r650",
	}
	err := mysql.DB.Debug().Create(&m).Error
	if err != nil {
		return nil, err
	}

	return &homerpc.ResterResponse{
		Uid: int64(m.ID),
	}, nil
}
